<template>
  <a-upload
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :before-upload="beforeAvatarUpload"
    action="/api/image/avatar/upload"
    @change="handleAvatarChange"
    :headers="headers"
  >
    <img
      v-if="avatar"
      :src="avatar"
      alt="avatar"
      :style="{ width: '100px', height: '100px' }"
    />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">点击上传</div>
    </div>
  </a-upload>
</template>
<script lang="ts" setup>
import storage from "store";
import { ref, onMounted, computed, watch, nextTick } from "vue";
import { message } from "ant-design-vue";
import {
  UserOutlined,
  PlusOutlined,
  LoadingOutlined,
} from "@ant-design/icons-vue";
import ResultEnum from "@/config/ResultEnum";

interface PropsConfig {
  data: any;
}

/**
 * 图片格式
 */
interface ImgSource {
  480: string;
  720: string;
  1024: string;
  org: string;
}

const props = withDefaults(defineProps<PropsConfig>(), {
  data: String as any,
});

const emit = defineEmits(["update:value"]);
const data = ref({});
const loading = ref(false);
const avatar = ref("");
const headers = ref({
  token: storage.get("token"),
});

function getBase64(img: any, callback: any) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

//设置初始值
const setData = (source: any) => {
  data.value = source;
  avatar.value = source;
};

//获取上传数据
const getData = () => {
  return data.value;
};

/**
 * 上传事件
 * @param info
 */
const handleAvatarChange = (info: any) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }

  if (info.file.status === "done") {
    let res = info.file.response;
    console.log(res);
    if (res.code == ResultEnum.SUCCESS_CODE) {
      data.value = res.result[0].savePath;
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (base64Url: any) => {
        //imageUrl.value = base64Url;
        avatar.value = base64Url;
        loading.value = false;
      });
    } else {
      message.error(res.message);
    }
  }

  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};

const beforeAvatarUpload = (file: any) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";

  if (!isJpgOrPng) {
    message.error("只能上传jpg格式图片!");
  }

  const isLt2M = file.size / 1024 / 1024 < 1;

  if (!isLt2M) {
    message.error("图片必须小于1M");
  }

  return isJpgOrPng && isLt2M;
};

watch(
  () => props.data,
  (newVal: any) => {
    console.log("头像newVal is ", newVal);
    data.value = newVal;
    if (newVal) {
      avatar.value =
        import.meta.env.VITE_APP_IMG_SERVER + (data.value as string);
    } else {
      avatar.value = "";
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => avatar.value,
  (value: string) => {
    emit("update:value", value);
  }
);

onMounted(() => {
  //avatar.value = props.value;
});

defineExpose({
  setData,
  getData,
  headers,
});
</script>
